#!/usr/bin/env python
# encoding:utf-8
# @Time   : 2018/10/06
# @File   : baseHandler.py

from tornado.web import RequestHandler
import json
# 白名单ip定义 '*'表示所有
IPs = ['*']


class BaseHandler(RequestHandler):
    @property
    def log(self):
        return self.application.logger

    def prepare(self):
        if not self.is_white_ip(): return
        """预解析json数据"""
        if self.request.headers.get("Content-Type", "").startswith("application/json"):
            self.json_args = json.loads(self.request.body)
        else:
            self.json_args = {}
        post_data = {}
        for key in self.request.arguments:
            post_data[key] = self.get_argument(key)
        self.log.info(f"收到请求:{self.request.uri},参数: {self.json_args}{str(post_data)}")



    def set_default_headers(self):
        """设置默认json格式"""
        self.set_header("Content-Type", "application/json; charset=UTF-8")


    def is_white_ip(self):
        if self.request.remote_ip not in IPs and '*' not in IPs:
            self.log.info("非ip白名单请求:" + self.request.remote_ip)
            self.write_error(408)
            return False
        else:
            return True